(function (doc) {
  function Modal() {
    var oModal = doc.getElementsByClassName('modal')[0],
      opt = getOptions(oModal);

    this.oModal = oModal;
    this.titleName = opt.titleName;
    this.content = opt.content;
    this.movable = opt.movable;
    this.titleColor = opt.titleColor;
  }

  Modal.prototype.initPlugin = function () {
    render.call(this);

    var oTitle = this.oModal.getElementsByClassName('title')[0],
      oContent = this.oModal.getElementsByClassName('content')[0],
      oCloseBtn = this.oModal.getElementsByClassName('icon-close')[0],
      oConfirmBtn = this.oModal.getElementsByClassName('confirm')[0],
      oCancelBtn = this.oModal.getElementsByClassName('cancel')[0];

    setOptions.call(this, { oTitle, oContent });
    bindEvent.call(this, { oTitle, oCloseBtn, oConfirmBtn, oCancelBtn });
  };

  function createModal() {
    return `
      <div class="modal-wrap">
        <div class="modal-hd">
          <h3 class="title"></h3>
          <i class="icon-close">✕</i>
        </div>
        <div class="modal-bd">
          <h2 class="content"></h2>
          <div class="btn-group">
            <button class="confirm">Confirm</button>
            <button class="cancel">Cancel</button>
          </div>
        </div>
    </div>
    `;
  }

  function render() {
    this.oModal.innerHTML = createModal();
  }

  function setTitle(el, val) {
    el.innerText = val;
  }

  function setContent(el, val) {
    el.innerText = val;
  }

  function setTitleColor(el, val) {
    var oParent = el.parentNode;
    oParent.style.backgroundColor = val;
  }

  function getOptions(el) {
    return JSON.parse(el.getAttribute('data-config'));
  }

  function setOptions(el) {
    var { oTitle, oContent } = el;
    setTitle(oTitle, this.titleName);
    setContent(oContent, this.content);
    setTitleColor(oTitle, this.titleColor);
  }

  function handleTitleClick(oTitle, e) {
    oTitle.style.cursor = 'move';
    elemDrag(elemChildren(this.oModal)[0]);
  }

  function handleConfirmBtnClick() {
    hideModal.call(this);
  }

  function handleCancelClick() {
    hideModal.call(this);
  }

  function handleCloseBtnClick(e) {
    hideModal.call(this);
  }

  function hideModal() {
    this.oModal.style.display = 'none';
  }

  function bindEvent(el) {
    var { oTitle, oCloseBtn, oConfirmBtn, oCancelBtn } = el;
    addEvent(oTitle, 'click', handleTitleClick.bind(this, oTitle));
    addEvent(oCloseBtn, 'click', handleCloseBtnClick.bind(this), false);
    addEvent(oConfirmBtn, 'click', handleConfirmBtnClick.bind(this), false);
    addEvent(oCancelBtn, 'click', handleCancelClick.bind(this), false);
  }

  window.Modal = Modal;
})(document);
